package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Company;
import service.CompanyService;
import service.impl.CompanyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Author: 燕子豪
 * @Date: 2022/12/18 11:11
 */
@WebServlet("/companyUpdate")
public class CompanyUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        CompanyService companyService = new CompanyServiceImpl();

        //解析前段json数据
        BufferedReader bufferedReader = new BufferedReader(request.getReader());
        String line = null;
        final StringBuilder json = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //new一个race用于接收数据
        Company company = new Company();
        company.setCname(jsonObject.getString("cname"));
        company.setCpassword(jsonObject.getString("cpassword"));
        company.setCemail(jsonObject.getString("cemail"));
        company.setLogo(jsonObject.getString("logo"));
        company.setCphone(jsonObject.getString("cphone"));
        company.setDesc(jsonObject.getString("desc"));

        //执行方法并存储返回结果
        JSONObject message = new JSONObject();
        if (companyService.update(company)) {
            message.put("statue", "1");
            message.put("raceMsg", "更新成功");
        }else{
            message.put("statue", "0");
            message.put("raceMsg", "更新失败");
        }
        response.getWriter().write(message.toString());
    }
}
